<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .mouse {
        width: 100px;
        height: 100px;
        background: gray;
        position: fixed;
      }

      .selected {
        border: 5px solid blue;
      }
    </style>
  </head>
  <body>
    <div class="mouse"></div>
    <div class="mouse"></div>
    <div class="mouse"></div>
    <div class="mouse"></div>
    <div class="mouse"></div>
    <script>
      // 1. 选中要移动的对象
      let mouse = null;
      document.onclick = function (e) {
        // 判断点击的是否是mouse
        if (e.target.classList.contains("mouse")) {
          // 如果是mouse，将目标赋值给变量let mouse
          mouse = e.target;

          // 取消之前的选中样式
          document
            .querySelectorAll(".mouse.selected")
            .forEach((el) => el.classList.remove("selected"));

          // 加上选中的样式
          mouse.classList.add("selected");
        }
      };
      // 2. 监听键盘方向键
      window.onkeydown = function (e) {
        if (mouse) {
          const { left, top } = mouse.getBoundingClientRect();
          if (e.key === "ArrowUp") {
            mouse.style.top = top - 20 + "px";
          }
          if (e.key === "ArrowDown") {
            mouse.style.top = top + 20 + "px";
          }
          if (e.key === "ArrowLeft") {
            mouse.style.left = left - 20 + "px";
          }
          if (e.key === "ArrowRight") {
            mouse.style.left = left + 20 + "px";
          }
        }
      };
    </script>
  </body>
</html>
